import asyncore
import threading
import time
import logging
_LOGGER = logging.getLogger(__name__)
class TcpClient(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.messages = []
        self.host = host
        self.port = port
        self.onmessage = None
        self.on_close = None

    def connect(self):
        self.create_socket()
        super().connect((self.host,self.port))
        asyncore.loop()

    def handle_connect(self):
        pass
        #_LOGGER.error('连接完成')

    def handle_error(self) -> None:
        pass

    def handle_read(self):
        buf = self.recv(1024)
        if buf==b'':
            _LOGGER.error('连接断开，10秒后重连')
            self.close()
            time.sleep(10)
            self.connect()
        if not self.onmessage is None:
            self.onmessage(buf) 
    
class ClientThread(threading.Thread):
    def __init__(self,host,port):
        threading.Thread.__init__(self)
        self.client = TcpClient(host, port)

    def stop(self):
        self.client.close()
        asyncore.close_all()

    def set_call_fn(self,fn):
        self.client.onmessage = fn

    def set_on_close(self,fn):
        self.client.on_close = fn

    def send_data(self,data):
        self.client.send(bytes(data))
        #self.client.messages = data
    
    def run(self):
        self.client.connect()
        